<?php

namespace App\Jobs\Finance;

use App\Jobs\Finance\Traits\CommonBranchBillTrait;
use App\Jobs\Finance\Traits\CreateBillTrait;
use App\Models\Finance\FinanceBranchBill;
use App\Models\Finance\FinanceBranchDetailBill;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ShopReassignBillJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, CreateBillTrait, CommonBranchBillTrait;

    public object|null $shopDetail=null;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($shopDetail)
    {
        //
        $this->shopDetail=$shopDetail;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        $subAccounts=$this->shopDetail->subAccounts;
        if(count($subAccounts)>0){
            $customer=$this->shopDetail->customer;
            $branchData=$this->getBranchData($this->shopDetail,$customer);
            $branchBill=FinanceBranchBill::create($branchData);
            $shopConsult=0;
            if($subAccounts && count($subAccounts)){
                $startEndArr=[];
                foreach ($subAccounts as $subAccount){
                    //子帐号账单详情
                    $accountData=$this->getAccountData($branchBill,$subAccount,$this->shopDetail);
                    $shopConsult+=$accountData['consult_quantity'];
                    $detailBill=FinanceBranchDetailBill::create($accountData);
                    $startEndArr[]=$this->getBranchServicePeriod($accountData['service_period']);
                    $servicePrice=$accountData['service_price'];
                }
                $this->updateBranchTotalData($branchBill,$shopConsult,$startEndArr,$servicePrice);
            }
        }

    }

    //分部账单数据
    public function getBranchData($shopDetail,$customer){
        $period=$this->getReassignStartEnd($shopDetail,$customer);
        return [
            'is_reassign_bill'=>1,
            'department_id'=>$shopDetail->department_two_id,
            'department_name'=>$shopDetail->departmentTwo->name??'',
            'bill_date'=>date('Y-m'),
            'wx_group'=>$shopDetail->quotaionInfo->wx_group??'',
            'bill_period_start'=>$period['period_start'],
            'bill_period_end'=>$period['period_end'],
            'bill_type'=>$customer->advance_order,
            'bill_month'=>$this->getBillMonth($customer),
            'company_name'=>$customer->company_name,
            'customer_id'=>$customer->id,
        ];
    }
    //获取账单周期
    public function getBillMonth($customer){
        $day = date('d');
        $lastMonth=date("m", strtotime(-$day.' day'));
        $year=date('Y');
        if($lastMonth==12){
            $year-=1;
        }
        //定时任务生成过账单
        if($this->checkCustomerMonthBill($customer)){
            return date('Y').'年'.date('m').'月';
        }
        //定时任务还没生成账单
        if($customer->advance_order==1){
            return $year.'年'.$lastMonth.'月';
        }
        return $year.'年'.$lastMonth.'-'.date('m').'月';
    }
    //获取账单开始结束时间
    public function getReassignStartEnd($shopDetail,$customer){

        $start=date('Y-m-1');
        $end=date('Y-m-d');
        $today=date('d');
        $lastMonth=$this->getLastMonth();
        if($customer){
            if($customer->advance_order==1){
                if($shopDetail->reassign_time && strtotime($shopDetail->reassign_time)>strtotime($start)){
                    $start=date('Y-m-d',strtotime($shopDetail->reassign_time));
                }
            }else{
                $thisMonthSettle=date('Y-m').'-'.$customer->settle_date;
                if((int)$today>$customer->settle_date){
                    if($shopDetail->reassign_time && strtotime($shopDetail->reassign_time)>strtotime($thisMonthSettle)){
                        $start=date('Y-m-d',strtotime($shopDetail->reassign_time));
                    }else{
                        $start=$thisMonthSettle;
                    }
                }else{
                    $start=$lastMonth.'-'.$customer->settle_date;
                    if($shopDetail->reassign_time && strtotime($shopDetail->reassign_time)>strtotime($start) && strtotime($shopDetail->reassign_time)<strtotime($thisMonthSettle)){
                        $start=date('Y-m-d',strtotime($shopDetail->reassign_time));
                    }
                }
            }
        }
        return [
            'period_start'=>$start,
            'period_end'=>$end,
        ];
    }
    //分部子账号账单数据
    public function getAccountData($branchBill,$subAccount,$shopDetail){
        $departQuote=$this->getDepartmentQuote($shopDetail);
        $serviceStartEnd=$this->getServicePeriod($subAccount,$branchBill->bill_period_start,$branchBill->bill_period_end);
        $consult=$this->getConsult($subAccount,$branchBill->bill_period_start,$branchBill->bill_period_end);
        $overTimefee=$this->getOvertimeFee($subAccount,$branchBill->bill_period_start,$branchBill->bill_period_end);
        return [
            'branch_bill_id'=>$branchBill->id,
            'shop_id'=>$this->shopDetail->id,
            'shop_name'=>$this->shopDetail->shop_name,
            'sub_account_id'=>$subAccount->id,
            'sub_account'=>$subAccount->sub_account,
            'service_period'=>$serviceStartEnd['start'].'-'.$serviceStartEnd['end'],
            'service_days'=>$serviceStartEnd['service_days'],
            'consult_column'=>$consult['column'],
            'consult_quantity'=>$consult['quantity'],
//            'shop_other_fee'=>$account->shop_other_fee,
            'overtime_fee'=>$overTimefee->sum('price'),
            'penalty_amount'=>$this->getPenalty('b_service_couplet',$subAccount->id, $branchBill->bill_period_start,$branchBill->bill_period_end),
            'department_quote_id'=>$departQuote['department_quote_id'],
            'service_price'=>$departQuote['service_price'],
        ];
    }

    //获取部门报价
    public function getDepartmentQuote($shopDetail){
        $departQuote=$shopDetail->quotaionInfo->departmentQuote??null;
        return [
            'department_quote_id'=>$departQuote->id??'',
            'service_price'=>$departQuote->price_content??'',
        ];
    }
    //更新分部账单分组数据
    public function updateBranchTotalData($branchBill,$shopConsult,$startEndArr,$servicePrice){
        $quoteTotal=$shopConsult;
        $totalDays=$this->getConsultDays($startEndArr);
        $dayAverage=$totalDays?round($quoteTotal/$totalDays,1):0;
        $price=$this->selectQuoteFinal($servicePrice,$dayAverage);
        $data=[
            'quote_total_consult'=>$quoteTotal,
            'total_quote_consult_days'=>$totalDays,
            'quote_day_average_consult'=>$dayAverage,
            'service_quote_final'=>$price,
            'shop_other_fee'=>$this->getShopFee($this->shopDetail,$shopConsult,$startEndArr),
        ];
        $branchBill->billDetail()->update($data);

        $branchData=[
            'total_consult'=>$shopConsult,
        ];
        return $branchBill->update($branchData);
    }


}
